import React from 'react';
import '../../../../style/user.css'
class Upload extends React.Component {
    constructor() {
        super();
        this.state = {
            filedis:'+',
            display:2
        }
        this.changeFile.bind(this)
        this.triggerClick.bind(this)
    }
    //点击事件，如果input中file为空则弹出文件选择让用户选择文件上传，否则代表删除这个文件
    triggerClick=()=>{
        if(this.props.fileitem=="")
            this.fileInput.click()
        else{
            this.props.fileTo(null,this.props.id)
            this.fileInput.value=""
        }
    }
    changeFile=(e)=>{
        this.file=e.target.files
        if(this.file[0]==null)
            return;
        this.props.fileTo(this.file[0],this.props.id,this.props.filetype)
    }
    //根据文件类型设置display的值，display用来决定显示预览图片还是视屏
    setWindow=(file)=>{
        if(this.props.filetype=="videos"){
            const blob = new Blob([file]), // 文件转化成二进制文件
                url = URL.createObjectURL(blob); //转化成url
            this.setState({
                filedis:url,
                display:3
            })
        }
        else{
            const type=this.props.filetype
            const reader = new FileReader();
            reader.readAsDataURL(file);
            reader.onload = () =>{
                if(type=="documents") {
                    this.setState({
                        filedis:file.name,
                        display:2
                    })
                }else this.setState({
                        filedis:reader.result,
                        display:1
                      })
            }
        }
    }
    componentWillReceiveProps(nextProps){
        if(nextProps.fileitem=="")
            this.state = {
                filedis:'+',
                display:2
            }
        else this.setWindow(nextProps.fileitem)
    }
    render() {
        return(
            <td>
                <div className="choosePic" onClick={this.triggerClick}>
                    {this.state.display==1&&<img src={this.state.filedis}/>}
                    {this.state.display==2&&<span>{this.state.filedis}</span>}
                    {this.state.display==3&&<video controls src={this.state.filedis}/>}
                    <span>宣传图</span>
                </div>
                <input type="file" ref={(input) => { this.fileInput = input; }} style={{display:"none"}} className="fileimg" onChange={this.changeFile}/>
            </td>
        );
    }
}
export default Upload
